package com.yesin.goods.service;

import com.yesin.geteway.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;


@Service
public class GoodsHtmlService {
    @Autowired
    private TemplateEngine engine;

    @Autowired
    private GoodsService goodsService;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);

    public void createHtml(Long spuId){
        // 初始化运行上下文
        Context context = new Context();
        context.setVariables(this.goodsService.loadData(spuId));
        // 把静态文件生成到服务器本地
        PrintWriter printWriter = null;
        try {
            File file = new File("F:\\Tools\\nginx\\html\\item\\" + spuId + ".html");
            printWriter = new PrintWriter(file);
            this.engine.process("item", context, printWriter);
            LOGGER.info("页面静态化成功:{}", spuId);
        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{}," + e, spuId);
        }finally {
            if (printWriter != null){
                printWriter.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(() -> createHtml(spuId));
    }

    /**
     * 删除静态页面
     * @param spuId
     */
    public void deleteHtml(Long spuId) {
        File file = new File("F:\\Tools\\nginx\\html\\item\\" + spuId + ".html");
        file.deleteOnExit();
    }
}
